package fileService

import (
	"bytes"
	"fmt"
	"github.com/go-resty/resty/v2"
	"go-brouter/config"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"time"
)

//注意client 本身是连接池，不要每次请求时创建client
var (
	HttpClient = &http.Client{
		Timeout: 3 * time.Second,
	}
)

// 上传文件
// url                请求地址
// params        post form里数据
// nameField  请求地址上传文件对应field
// fileName     文件名
// file               文件
func UploadFile(url string, params map[string]string, nameField, fileName string, file io.Reader) ([]byte, error) {
	body := new(bytes.Buffer)

	writer := multipart.NewWriter(body)

	formFile, err := writer.CreateFormFile(nameField, fileName)
	if err != nil {
		return nil, err
	}

	_, err = io.Copy(formFile, file)
	if err != nil {
		return nil, err
	}

	for key, val := range params {
		_ = writer.WriteField(key, val)
	}

	err = writer.Close()
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequest("POST", url, body)
	if err != nil {
		return nil, err
	}
	//req.Header.Set("Content-Type","multipart/form-data")
	req.Header.Add("Content-Type", writer.FormDataContentType())

	resp, err := HttpClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	content, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	return content, nil
}

func UploadToServerResty(filename string) {
	// Create a Resty Client
	client := resty.New()
	// Single file scenario
	resp, err := client.R().
		SetFile(filename, "./uploadToServer/"+filename).
		SetFormData(map[string]string{
			"first_name":   "Jeevanandam",
			"last_name":    "M",
			"zip_code":     "00001",
			"city":         "my city",
			"access_token": "C6A79608-782F-4ED0-A11D-BD82FAD829CD",
		}).
		Post(config.ParamsConfig.GetString("remote.url"))
	if err != nil {
		fmt.Println(resp)
	}
}
